package jwt.util;

import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.charset.StandardCharsets;
import java.util.Base64;

public class ExcelAESDecryptor {
    private static final byte[] IV_BYTES = "ABCDEF1234123412".getBytes();
    public static void main(String[] args) {
        try {
            // 1. 配置参数
            String desktopPath = "C:\\Users\\95383\\Desktop\\";
            String inputFileName = "encrypted_data.xlsx"; // 输入文件名
            String outputFileName = "decrypted_data.xlsx"; // 输出文件名
            String key = "9e5702ead4d643fd"; // AES密钥（16字节）

            // 2. 读取Excel文件
            FileInputStream file = new FileInputStream(new File(desktopPath + inputFileName));
            Workbook workbook = WorkbookFactory.create(file);
            Sheet sheet = workbook.getSheetAt(0); // 获取第一个Sheet

            // 3. 遍历所有行
            for (Row row : sheet) {
                // 获取第一列单元格（索引0）
                Cell encryptedCell = row.getCell(0);
                if (encryptedCell == null) continue;

                // 读取加密文本
                String encryptedText = getCellValueAsString(encryptedCell);
                if (encryptedText.isEmpty()) continue;

                // 4. 执行解密
                String decryptedText = decrypt(encryptedText, key);
                System.out.println("第一次解密:"+decryptedText);
                //2次解密
                decryptedText = decrypt(decryptedText,"1234123412ABCDEF","AES/CBC/PKCS5Padding");
                System.out.println("第二次解密:"+decryptedText);

                // 5. 写入第二列（索引1）
                Cell decryptedCell = row.createCell(1);
                decryptedCell.setCellValue(decryptedText);
            }

            // 6. 保存修改到新文件
            FileOutputStream outFile = new FileOutputStream(new File(desktopPath + outputFileName));
            workbook.write(outFile);
            workbook.close();
            System.out.println("解密完成！文件已保存至桌面：" + outputFileName);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 解密方法（与之前相同）
    private static String decrypt(String encryptedText, String key) throws Exception {
        byte[] keyBytes = key.getBytes("UTF-8");
        if (keyBytes.length != 16 && keyBytes.length != 24 && keyBytes.length != 32) {
            throw new IllegalArgumentException("密钥长度必须为16、24或32字节");
        }
        SecretKeySpec secretKey = new SecretKeySpec(keyBytes, "AES");
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
        cipher.init(Cipher.DECRYPT_MODE, secretKey);
        byte[] decryptedBytes = cipher.doFinal(Base64.getDecoder().decode(encryptedText));
        return new String(decryptedBytes, "UTF-8");
    }

    // 通用方法：获取单元格内容为字符串
    private static String getCellValueAsString(Cell cell) {
        if (cell == null) return "";
        DataFormatter formatter = new DataFormatter();
        return formatter.formatCellValue(cell).trim();
    }
    public static String decrypt(String str, String key,String transformation) {

        byte[] raw = key.getBytes(StandardCharsets.UTF_8);
        SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
        IvParameterSpec iv = new IvParameterSpec(IV_BYTES);
        try {
            Cipher cipher = null;

            cipher = Cipher.getInstance(transformation);
            cipher.init(Cipher.DECRYPT_MODE, skeySpec,iv);
            //先用base64解密
            byte[] encrypted1 = org.apache.commons.codec.binary.Base64.decodeBase64(str);//new Base64().decode(str);
            byte[] original = cipher.doFinal(encrypted1);
            String originalString = new String(original,StandardCharsets.UTF_8);
            return originalString;
        } catch (Exception e) {
            System.out.println("解密异常");
        }
        return null;
    }
}
